package com.yf.controller.ai.chat;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yf.model.ai.form.ConversationBindMaskForm;
import com.yf.model.ai.form.ConversationBindToolsForm;
import com.yf.model.ai.form.UserChatConfigForm;
import com.yf.model.ai.query.UserChatConversationPageQuery;
import com.yf.model.ai.query.UserChatMessagePageQuery;
import com.yf.model.ai.query.UserChatToolPageQuery;
import com.yf.model.ai.vo.UserChatConversationDetailVO;
import com.yf.model.ai.vo.UserChatConversationVO;
import com.yf.model.ai.vo.UserChatMaskVO;
import com.yf.model.ai.vo.UserChatMessageVO;
import com.yf.model.ai.vo.UserChatToolProviderVO;
import com.yf.model.ai.vo.UserChatToolVO;
import com.yf.rate_limiting.annotation.PreventDuplicateSubmit;
import com.yf.result.PageResult;
import com.yf.result.Result;
import com.yf.service.chat.IUserChatService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户聊天控制层
 *
 * @author : YiFei
 * @since : 2025/7/12 11:47
 */
@Tag(name = "用户聊天控制器")
@RestController
@RequestMapping("ai/user/chat")
@RequiredArgsConstructor
public class UserChatController {

    private final IUserChatService userChatService;

    @Operation(summary = "查询AI会话列表")
    @GetMapping("/conversations")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    public PageResult<UserChatConversationVO> getAiConversationPage(@ParameterObject @Validated UserChatConversationPageQuery queryParams) {
        IPage<UserChatConversationVO> result = userChatService.getAiConversationPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "查询AI消息记录表")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @GetMapping("/messages")
    public PageResult<UserChatMessageVO> getAiMessagePage(@ParameterObject @Validated UserChatMessagePageQuery queryParams) {
        IPage<UserChatMessageVO> result = userChatService.getAiMessagePage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "查询AI会话详情")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @GetMapping("/{conversationId}/detail")
    public Result<UserChatConversationDetailVO> getConversationDetail(@PathVariable Long conversationId) {
        UserChatConversationDetailVO result = userChatService.getConversationDetail(conversationId);
        return Result.success(result);
    }

    @Operation(summary = "获取草稿AI会话")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @GetMapping("/drafts")
    public Result<Long> getDraftConversations() {
        Long draftConversationId = userChatService.getDraftConversations();
        return Result.success(draftConversationId);
    }

    @Operation(summary = "查询所有 Tool Provider")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @GetMapping("/tool-provider")
    public Result<List<UserChatToolProviderVO>> getToolProvider() {
        List<UserChatToolProviderVO> toolProviders = userChatService.getToolProvider();
        return Result.success(toolProviders);
    }

    @Operation(summary = "修改AI会话配置")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @PutMapping("/{conversationId}/config")
    public Result<Boolean> updateConversationConfig(@PathVariable Long conversationId,
                                                    @RequestBody @Validated UserChatConfigForm form) {
        Boolean isUpdate = userChatService.updateConversationConfig(conversationId, form);
        return Result.judge(isUpdate);
    }

    @Operation(summary = "AI调整会话标题")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @PutMapping("/{conversationId}/ai-title")
    public Result<String> updateAiConversationTitle(@PathVariable Long conversationId) {
        String updateName = userChatService.updateAiConversationTitle(conversationId);
        return Result.success(updateName);
    }

    @Operation(summary = "查询所有面具")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @GetMapping("/masks")
    public Result<List<UserChatMaskVO>> getAllMasks(@RequestParam(required = false) String maskName) {
        // 后续面具多则可以考虑分页查询
        List<UserChatMaskVO> maskVOS = userChatService.getAllMasks(maskName);
        return Result.success(maskVOS);
    }

    @Operation(summary = "查询所有工具")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @GetMapping("/tools")
    public PageResult<UserChatToolVO> getToolPage(@ParameterObject @Validated UserChatToolPageQuery queryParams) {
        IPage<UserChatToolVO> result = userChatService.getToolPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "修改会话标题")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @PutMapping("/{conversationId}/title")
    public Result<Boolean> updateConversationTitle(@PathVariable Long conversationId, @RequestParam String title) {
        Boolean isUpdate = userChatService.updateConversationTitle(conversationId, title);
        return Result.judge(isUpdate);
    }

    @Operation(summary = "删除会话")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @DeleteMapping("/{conversationIds}")
    public Result<Boolean> removeConversation(@Parameter(description = "ids 以 , 分隔") @PathVariable String conversationIds) {
        Boolean isUpdate = userChatService.removeConversation(Arrays.stream(conversationIds.split(","))
                .map(Long::parseLong).collect(Collectors.toSet()));
        return Result.judge(isUpdate);
    }

    @Operation(summary = "删除会话聊天消息")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @DeleteMapping("/{messageId}/{conversationId}")
    public Result<Boolean> removeMessage(@PathVariable Long messageId, @PathVariable Long conversationId) {
        boolean isRemoved = userChatService.removeMessage(messageId, conversationId);
        return Result.judge(isRemoved);
    }

    @Operation(summary = "会话绑定面具")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @PostMapping("/bind-mask")
    public Result<Boolean> conversationBindMask(@RequestBody ConversationBindMaskForm form) {
        boolean isBound = userChatService.conversationBindMask(form.getConversationId(), form.getMaskId());
        return Result.judge(isBound);
    }

    @Operation(summary = "会话绑定工具集合")
    @PreventDuplicateSubmit
    @PreAuthorize("@permission.checker('ai:user:chat')")
    @PostMapping("/bind-tools")
    public Result<Boolean> conversationBindTools(@RequestBody ConversationBindToolsForm form) {
        boolean isBound = userChatService.conversationBindTools(form.getConversationId(), form.getToolIds());
        return Result.judge(isBound);
    }

}
